package com.dymall.interceptor;

import com.dymall.common.utils.UserContext;
import com.dymall.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 实现Spring MVC 拦截器接口 HandlerInterceptor ，用于在请求处理前后执行逻辑
 */
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtTool jwtTool;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 请求进入 Controller 前调用，这里用来验证 token 并设置当前用户
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的 token
        String token = request.getHeader("authorization");
        // 2.校验token
        Long userId = jwtTool.parseToken(token, stringRedisTemplate);
        // 2.1 、刷新token
        stringRedisTemplate.expire("login:token:"+token, 20, TimeUnit.MINUTES);//刷新过期时间
        // 3.将用户ID存入上下文
        UserContext.setUser(userId);
        // 4.放行
        return true;
    }

    /**
     * 请求结束后调用，用于清理线程局部变量（防止内存泄漏）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserContext.removeUser();
    }
}
